package com.qzdsoft.erpcloud.service.pu.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qzdsoft.erpcloud.domain.pu.PurchaseInquiry;
import com.qzdsoft.erpcloud.domain.pu.PurchaseInquiryDetail;
import com.qzdsoft.erpcloud.mapper.com.CustomerSupplierStatementQueryMapper;
import com.qzdsoft.erpcloud.mapper.com.SupplierCustomerMapper;
import com.qzdsoft.erpcloud.mapper.proj.MaterialQueryMapper;
import com.qzdsoft.erpcloud.mapper.pu.PurchaseInquiryDetailMapper;
import com.qzdsoft.erpcloud.mapper.pu.PurchaseInquiryDetailQueryMapper;
import com.qzdsoft.erpcloud.mapper.pu.PurchaseInquiryMapper;
import com.qzdsoft.erpcloud.service.pu.PurchaseInquiryDetailService;
import com.qzdsoft.erpcloud.vo.com.CustomerSupplierStatementInfo;
import com.qzdsoft.erpcloud.vo.proj.MaterialInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseInquiryDetailEditInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseInquiryDetailEditItemInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseInquiryDetailInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseInquiryDetailQueryInfo;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;
import com.qzdsoft.vo.TypeInfo;

@Service
public class PurchaseInquiryDetailServiceImpl implements PurchaseInquiryDetailService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(PurchaseInquiryDetailServiceImpl.class);
    
	@Autowired
	private PurchaseInquiryDetailQueryMapper purchaseInquiryDetailQueryMapper;
	
	@Autowired
	private MaterialQueryMapper materialMapper;
	
	@Autowired
	private PurchaseInquiryDetailMapper purchaseInquiryDetailMapper;
	
	@Autowired
	private CustomerSupplierStatementQueryMapper customerSupplierStatementQueryMapper;
	
	@Autowired
	private SupplierCustomerMapper supplierCustomerMapper;
	
	@Autowired
	private PurchaseInquiryMapper purchaseInquiryMapper;
	
	@Override
	public List<PurchaseInquiryDetailInfo> selectDetailBy(PurchaseInquiryDetailQueryInfo info) {
		return purchaseInquiryDetailQueryMapper.selectById(info);
	}

	@Transactional
    @Override
    public Response<String> edit(PurchaseInquiryDetailEditInfo info)
    {
	    logger.debug("编辑采购询价单详情提交数据为空{}",info);
	    List<PurchaseInquiryDetailEditItemInfo> details = info.getItems();
	    if(CollectionUtils.isEmpty(details)) {
	        logger.error("编辑采购询价单详情提交数据为空");
	        return new Response<>(ResultEnum.ERROR);
	    }
	    int taxPrice=0,noTaxPrice=0,tax=0;
	    List<PurchaseInquiryDetail> adddetails = new ArrayList<PurchaseInquiryDetail>();//新增的采购询价单详情
	    List<PurchaseInquiryDetail> editDetails = new ArrayList<PurchaseInquiryDetail>();//修改的采购询价单详情
	    for(PurchaseInquiryDetailEditItemInfo d:details) {
	        PurchaseInquiryDetail detail = new PurchaseInquiryDetail();
	        if(!StringUtil.isEmpty(d.getId())) {
	            detail = purchaseInquiryDetailMapper.selectByPrimaryKey(d.getId());
	            if(detail==null) {
	                logger.error("编辑采购询价单明细时,根据id,没找到相应的明细数据，可能改明细不存在",d.getId());
	                throw new RuntimeException("编辑采购询价单明细时,根据id,没找到相应的明细数据，可能改明细不存在");
	            }
	            editDetails.add(detail);
	        }else {
	            //detail.setRequireTime(new Date());
	            detail.setDeliveryTime(new Date());
	            adddetails.add(detail);
	        }
	        detail.setBillId(info.getBillid());
	        detail.setBillNo(info.getBillno());
	        detail.setMaterialId(d.getMaterialId());
	        MaterialInfo material = materialMapper.selectById(d.getMaterialId());
	        if(material==null) {
	            logger.error("物料编码错误，根据物料编码：{},没找到对应的物料信息");
	            throw new RuntimeException("物料编码错误");
	        }
	        //物料有关设置
	        detail.setMaterialCoding(material.getCode());
	        detail.setMaterialSpec(material.getSpec());
	        detail.setMaterialTypeId(material.getTypeid());
	        detail.setMaterialName(material.getName());
	        detail.setMeasurementUId(material.getMearsureUintid());
	        detail.setsMaterialCoding(material.getAliasCode());
	        detail.setMaterialAliasId(material.getAliasId());
	        detail.setsMaterialName(material.getAliasName());
	        detail.setsMaterialSpec(material.getAliasSpec());
	        detail.setMaterialName(material.getName());
	        detail.setBrandId(material.getBrandid());
	        
	        detail.setDeliveryTime(detail.getDeliveryTime());
	        detail.setEffectialType(detail.getEffectialType());
	        detail.setEffectialTime(detail.getEffectialTime());
	        
	        detail.setPrice(d.getPrice());
	        detail.setAmount(d.getAmount());
	        
	        //CustomerSupplierStatementInfo statement = customerSupplierStatementQueryMapper.selectById(d.getSettlementId());
	        //detail.setStatementCurrencyId(statement.getCurrency());
	        //detail.setStatementDays(statement.getDates());
	        //detail.setStatementExchangeRate(statement.getExchangeRate());
	       
	        //设置税率
	        //TypeInfo taxInfo = supplierCustomerMapper.selectTaxInfo(info.getCompanyid(), info.getSupplierid());
	        //detail.setStatementTaxRate(Integer.parseInt(taxInfo.getValue()));
	        //detail.setTaxRate(Integer.parseInt(taxInfo.getValue()));
	        
	        //int price = d.getPrice()*d.getNum();
	        //noTaxPrice += price;
	        //tax += Integer.parseInt(taxInfo.getValue())*price/100;
	    }
	    //taxPrice = tax+noTaxPrice;
	    PurchaseInquiry puInquiry = purchaseInquiryMapper.selectByPrimaryKey(info.getBillid());
	    //puInquiry.setTax(tax);
	    //puInquiry.setNoTaxPrice(noTaxPrice);
	    //puInquiry.setTaxPrice(taxPrice);
	    int count = purchaseInquiryMapper.updateByPrimaryKey(puInquiry);
	    if(count!=1) {
	        logger.error("编辑采购询价单明细错误，更新数据不对updatecount={}",count);
	        throw new RuntimeException("编辑采购询价单明细错误，更新数据不对updatecount="+count);
	    }
	    if(!CollectionUtils.isEmpty(adddetails)) {
	        count = purchaseInquiryDetailMapper.insertList(adddetails);
	        if(count!=adddetails.size()) {
	            logger.error("编辑采购询价单明细错误，更新数据不对updatecount={},提交新增数据条数：{}",count,adddetails.size());
	            throw new RuntimeException("编辑采购询价单明细错误，更新数据不对updatecount="+count);
	        }
	    }
	    
	    count = 0;
	    for(PurchaseInquiryDetail p:editDetails) {
	        count += purchaseInquiryDetailMapper.updateByPrimaryKey(p);
	    }
	    if(count!=editDetails.size()) {
            logger.error("编辑采购询价单明细错误，更新数据不对updatecount={},提交修改数据条数：{}",count,editDetails.size());
            throw new RuntimeException("编辑采购询价单明细错误，更新数据不对updatecount="+count);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }

    @Override
    public Response<String> remove(List<Integer> ids)
    {
        int counts = purchaseInquiryDetailMapper.deleteByIds(ids);
        if(counts!=ids.size()) {
            logger.error("编辑采购询价单明细错误，删除数据不对deletecount={},提交修改数据条数：{}",counts,ids.size());
            throw new RuntimeException("删除采购询价单明细错误，更新数据不对deletecount="+counts);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }

}
